package com.sample.extension;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.alfresco.repo.jscript.ScriptNode;
import org.alfresco.repo.processor.BaseProcessorExtension;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;

public class UpdateApprover extends BaseProcessorExtension
{

	private ServiceRegistry serviceRegistry;
	private AuthenticationComponent authenticationComponent;

	public void setAuthenticationComponent(
	        AuthenticationComponent authenticationComponent)
	{
		this.authenticationComponent = authenticationComponent;
	}

	public void setServiceRegistry(ServiceRegistry serviceRegistry)
	{
		this.serviceRegistry = serviceRegistry;
	}

	public void updateApprover(ScriptNode node, String userName)
	{
		updateApprover(node.getNodeRef(), userName);
	}

	public void updateApprover(final NodeRef node, final String userName)
	{
		RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>()
		{
			public Object execute() throws Exception
			{
				String user = authenticationComponent.getCurrentUserName();
				authenticationComponent.setSystemUserAsCurrentUser();

				addApprover(node,userName);

				if (user != null)
					authenticationComponent.setCurrentUser(user);
				return null;
			}

		};
		serviceRegistry.getTransactionService().getRetryingTransactionHelper()
		        .doInTransaction(txnWork, false, false);
	}

	protected void addApprover(NodeRef node, String userName)
    {
	    Date today=new Date();
	    DateFormat format=new SimpleDateFormat("yyyy/MM/dd");
	    String text="Aproved by "+userName+" on "+format.format(today);
	    NodeService nodeService=serviceRegistry.getNodeService();
	    if(!nodeService.hasAspect(node,SampleModel.ASPECT_APPROVED))
	    	nodeService.addAspect(node,SampleModel.ASPECT_APPROVED,null);
	    @SuppressWarnings("unchecked")
        List<String> approvers=(List<String>) nodeService.getProperty(node,SampleModel.PROP_APPROVERS);
	    approvers=approvers!=null?new ArrayList<String>(approvers):new ArrayList<String>();
	    approvers.add(text);
	    nodeService.setProperty(node,SampleModel.PROP_APPROVERS,(Serializable) approvers);
    }
}
